/**
 * 
 */
package com.jushu.storbox.database;

import java.util.ArrayList;
import java.util.List;

import android.database.Cursor;

import com.jushu.storbox.ShareDriveApplication;
import com.jushu.storbox.entities.AlbumFileInfo;
import com.jushu.storbox.util.LogUtil;
import com.huawei.sharedrive.sdk.android.util.StringUtil;

/**
 *  Local Album Sync Data
 */
public class AlbumDao  extends BaseDao implements IAlbumDao {
	
	public final static String FILE_TABLE_NAME = TABLE_NAME_ALBUM_SYNC_LIST;
	public final static String LOG_TAG = "AlbumDao";
	
	public final static String REMAIN_COUNT = "remain_count";
	public final static String TOTAL_SIZE = "totalSize";
	public final static String BACKED_SIZE = "backed_size";

	@Override
	public AlbumFileInfo getFile(String fileName) {
		AlbumFileInfo fileInfo = null;
		try {
			if (StringUtil.isNotBlank(fileName)) {
				StringBuilder sb = new StringBuilder();
				sb.append("select * from ").append(FILE_TABLE_NAME);
				sb.append(" where ");
				sb.append(IBaseDao.file_name).append("=?");
				sb.append(" and ");
				sb.append(IBaseDao.owner_by).append("=?");
				
				Cursor cursor = this.getDb().rawQuery(sb.toString(),
						new String[] { fileName, ShareDriveApplication.getInstance().getWnerID()});
				if (cursor!=null && cursor.moveToFirst()) {
					fileInfo = new AlbumFileInfo();
					fileInfo.fromCursor(cursor);
				}
			}
		} catch (Exception e) {
			LogUtil.e(LOG_TAG, "getFile is fail:" + e.getMessage());
		}
		return fileInfo;
	}
	public AlbumFileInfo getFileByPath(String filePath) {
		AlbumFileInfo fileInfo = null;
		try {
			if (StringUtil.isNotBlank(filePath)) {
				StringBuilder sb = new StringBuilder();
				sb.append("select * from ").append(FILE_TABLE_NAME);
				sb.append(" where ");
				sb.append(IBaseDao.local_path).append("=?");
				sb.append(" and ");
				sb.append(IBaseDao.owner_by).append("=?");
				
				Cursor cursor = this.getDb().rawQuery(sb.toString(),
						new String[] { filePath, ShareDriveApplication.getInstance().getWnerID()});
				if (cursor!=null && cursor.moveToFirst()) {
					fileInfo = new AlbumFileInfo();
					fileInfo.fromCursor(cursor);
				}
			}
		} catch (Exception e) {
			LogUtil.e(LOG_TAG, "getFile is fail:" + e.getMessage());
		}
		return fileInfo;
	}

	@Override
	public void insertFile(AlbumFileInfo albumFileInfo) {
		try {
			this.getDb().insert(FILE_TABLE_NAME, null, albumFileInfo.toContentValues());
		} catch (Exception e) {
			LogUtil.e(LOG_TAG, "insertFile fail:" + e.getLocalizedMessage());
		}
	}


	@Override
	public void deleteFile(String fileName) {
		try {
			if (StringUtil.isNotBlank(fileName)) {
				this.getDb().execSQL("delete from " + FILE_TABLE_NAME + " where " + IBaseDao.file_name + " = ? and "+IBaseDao.owner_by +" = ?",
						new String[] { fileName , ShareDriveApplication.getInstance().getWnerID()});
			}
		} catch (Exception e) {
			LogUtil.e(LOG_TAG, "deleteFile is fail:" + e.getLocalizedMessage());
		}
	
	}
	
	public void deleteAlbumByPath(String filePath) {
		try {
			if (StringUtil.isNotBlank(filePath)) {
				this.getDb().execSQL("delete from " + FILE_TABLE_NAME + " where " + IBaseDao.local_path + " = ? and "+IBaseDao.owner_by +" = ?",
						new String[] { filePath , ShareDriveApplication.getInstance().getWnerID()});
			}
		} catch (Exception e) {
			LogUtil.e(LOG_TAG, "deleteFile is fail:" + e.getLocalizedMessage());
		}
	}
	
	@Override
	public int updateAlbumState(AlbumFileInfo albumFileInfo) {
		int ret = -1;
		try {
			String where = IBaseDao.local_path+"=? and "+BaseDao.owner_by +"=?";
			String[] whereArgs = new String[]{
					albumFileInfo.getFilePath(),
					ShareDriveApplication.getInstance().getWnerID()};
			ret = this.getDb().update(FILE_TABLE_NAME, 
					albumFileInfo.getStatusCV(), where, whereArgs);
		} catch (Exception e) {
			LogUtil.e(LOG_TAG, "deleteFile is fail:" + e.getLocalizedMessage());
		}
		return ret;
	}
	
	@Override
	public int updateAlbumStateToNew() {
		int ret = -1;
		try {
			String where = BaseDao.owner_by +"=?";
			String[] whereArgs = new String[]{ ShareDriveApplication.getInstance().getWnerID()};
			AlbumFileInfo albumFileInfo = new AlbumFileInfo();
			albumFileInfo.setStatus(IAlbumDao.ALBUM_STATUS_NEWFILE);
			ret = this.getDb().update(FILE_TABLE_NAME, 
					albumFileInfo.getStatusCV(), where, whereArgs);
		} catch (Exception e) {
			LogUtil.e(LOG_TAG, "deleteFile is fail:" + e.getLocalizedMessage());
		}
		return ret;
	}
	
	@Override
	public List<AlbumFileInfo> getNotBackedFileList() {
		List<AlbumFileInfo> folderList = new ArrayList<AlbumFileInfo>();
		try {
			String strSQL = "select * from " + FILE_TABLE_NAME + " where "
							+ IBaseDao.owner_by+"=? and " + IBaseDao.status+"=?";
			String[] selectionArgs = new String[] {ShareDriveApplication.getInstance().getWnerID(), ""+IAlbumDao.ALBUM_STATUS_NEWFILE};
			
			Cursor cursor = this.getDb().rawQuery(strSQL,selectionArgs);
			if (cursor != null) {
				while (cursor.moveToNext()) {
					AlbumFileInfo albumFile = new AlbumFileInfo();
					albumFile.fromCursor(cursor);
					folderList.add(albumFile);
				}
				cursor.close();
			}
		} catch (Exception e) {
			LogUtil.e(LOG_TAG, "getFileListPage is fail:" + e.getLocalizedMessage());
		}
		
		return folderList;
	}
	
	@Override
	public void deleteAllAlbumFiles() {
		try {
			this.getDb().execSQL("delete from " + FILE_TABLE_NAME + " where " +IBaseDao.owner_by +" = ?",
						new String[] {ShareDriveApplication.getInstance().getWnerID()});
		} catch (Exception e) {
			LogUtil.e(LOG_TAG, "deleteFile is fail:" + e.getLocalizedMessage());
		}
	}
	
	public void deleteAlbumFile(AlbumFileInfo info) {
		deleteAlbumByPath(info.getFilePath());
	}
	
	public void deleteAllAlbumFilesByFolder(String parentPath) {
		try {
			this.getDb().execSQL("delete from " + FILE_TABLE_NAME + " where " +IBaseDao.owner_by +" = ? and " + IBaseDao.parent_folder_id+"=?",
						new String[] {ShareDriveApplication.getInstance().getWnerID(), parentPath});
		} catch (Exception e) {
			LogUtil.e(LOG_TAG, "deleteFile is fail:" + e.getLocalizedMessage());
		}
	}
	
	@Override
	public long getLastUpdateTime(String objectId) {
		return 0;
	}

	@Override
	public void updateLastUpdateTime(String objectId) {
	}
	
	@Override
	public long getTotalAlbumSize() {
		long totalSize = 0;
		
		StringBuilder sb = new StringBuilder();
		sb.append("select ").append("sum(").append(IBaseDao.file_size).append(")").append(" as ").append(TOTAL_SIZE);
		sb.append(" from ").append(FILE_TABLE_NAME);
		sb.append(" where ");
		sb.append(IBaseDao.owner_by).append("=?");
		
		String[] selectionArgs = new String[] {ShareDriveApplication.getInstance().getWnerID()};

		Cursor cursor = this.getDb().rawQuery(sb.toString(), selectionArgs);
		if(cursor != null) {
			if(cursor.moveToNext()) {
				totalSize = cursor.getLong(cursor.getColumnIndex(TOTAL_SIZE));
			}
			cursor.close();
		}
		
		return totalSize;
	}
	
	@Override
	public long getUnBackupedSize() {
		long backedSize = 0;
		
		StringBuilder sb = new StringBuilder();
		sb.append("select ").append("sum(").append(IBaseDao.file_size).append(")").append(" as ").append(BACKED_SIZE);
		sb.append(" from ").append(FILE_TABLE_NAME);
		sb.append(" where ");
		sb.append(IBaseDao.owner_by).append("=?");
		sb.append(" and ");
		sb.append(IBaseDao.status).append("=?");
		
		
		String[] selectionArgs = new String[] {
				ShareDriveApplication.getInstance().getWnerID(),
				""+IAlbumDao.ALBUM_STATUS_NEWFILE
				};

		Cursor cursor = this.getDb().rawQuery(sb.toString(), selectionArgs);
		if(cursor != null) {
			if(cursor.moveToNext()) {
				backedSize = cursor.getLong(cursor.getColumnIndex(BACKED_SIZE));
			}
			cursor.close();
		}
		
		return backedSize;
	}
	
	@Override
	public int getRemainCount() {
		int remainCount = 0;
		
		StringBuilder sb = new StringBuilder();
		sb.append("select ").append("count(*)").append(" as ").append(REMAIN_COUNT);
		sb.append(" from ").append(FILE_TABLE_NAME);
		sb.append(" where ");
		sb.append(IBaseDao.owner_by).append("=?");
		sb.append(" and ");
		sb.append(IBaseDao.status).append("=?");
		
		
		String[] selectionArgs = new String[] {
				ShareDriveApplication.getInstance().getWnerID(),
				""+IAlbumDao.ALBUM_STATUS_NEWFILE
				};

		Cursor cursor = this.getDb().rawQuery(sb.toString(), selectionArgs);
		if(cursor != null) {
			if(cursor.moveToNext()) {
				remainCount = cursor.getInt(cursor.getColumnIndex(REMAIN_COUNT));
			}
			cursor.close();
		}
		
		return remainCount;
	}
	
	@Override
	public List<AlbumFileInfo> getFailedAlbumInfoList() {
		List<AlbumFileInfo> list = new ArrayList<AlbumFileInfo>();
		
		StringBuilder sb = new StringBuilder();
		sb.append("select ").append("*");
		sb.append(" from ").append(FILE_TABLE_NAME);
		sb.append(" where ");
		sb.append(IBaseDao.owner_by).append("=?");
		sb.append(" and ");
		sb.append(IBaseDao.status).append("=?");
		
		
		String[] selectionArgs = new String[] {
				ShareDriveApplication.getInstance().getWnerID(),
				""+IAlbumDao.ALBUM_STATUS_FAILURE
				};

		Cursor cursor = this.getDb().rawQuery(sb.toString(), selectionArgs);
		if(cursor != null) {
			while(cursor.moveToNext()) {
				AlbumFileInfo albumFile = new AlbumFileInfo();
				albumFile.fromCursor(cursor);
				list.add(albumFile);
			}
			cursor.close();
		}
		
		return list;
	}

}
